﻿namespace Common
{
    using System;
    using System.Collections.Generic;

    public static class ObjectsContainer
    {
        private static List<ICloneable> objects;

        static ObjectsContainer()
        {
            ObjectsContainer.objects = new List<ICloneable>();
        }

        public static void RegisterInstance<T>(ICloneable o) where T : class, ICloneable
        {
            foreach (var cloneable in ObjectsContainer.objects)
            {
                T temp = (cloneable as T);
                if (temp != null)
                {
                    throw new Exception("Instance of this type is already registered.");
                }
            }

            ObjectsContainer.objects.Add(o.Clone() as ICloneable);
        }

        public static object GetInstance<T>() where T : class, ICloneable
        {
            foreach (var cloneable in ObjectsContainer.objects)
            {
                var instance = (cloneable as T);

                if (instance != null)
                {
                    return instance;
                }
            }

            throw new Exception("Instance of this type is not registered.");
        }

        public static void ReleaseInstance<T>() where T : class, ICloneable
        {
            foreach (var cloneable in ObjectsContainer.objects)
            {
                var instance = (cloneable as T);

                if (instance != null)
                {
                    ObjectsContainer.objects.Remove(instance);
                    return;
                }
            }
        }
    }
}